import Vue from 'vue'
import Router from 'vue-router'
import storage from "storejs"

import login from '@/pages/login'
import index from '@/pages/index'
import detail from '@/pages/detail'
import room from '@/pages/room'
import userInfo from '@/pages/userInfo'

Vue.use(Router)

let router = new Router({
    mode: "history",
    routes: [
        {
            path: "/login",
            name: "login",
            component: login,
            meta: {
                isNeedLogin: false,
                title: "登录",
                pageWeight: -1          // 页面权重 为了是切动画
            }
        }, {
            path: "/",
            name: "index",
            component: index,
            meta: {
                isNeedLogin: true,
                title: "竞标列表",
                pageWeight: 0          // 页面权重 为了是切动画
            }
        },{
            path: "/detail/:id",
            name: "detail",
            component: detail,
            meta: {
                isNeedLogin: true,
                title: "竞标详情",
                pageWeight: 1          // 页面权重 为了是切动画
            }
        },{
            path: "/room/:id",
            name: "room",
            component: room,
            meta: {
                isNeedLogin: true,
                title: "竞标室",
                pageWeight: 2          // 页面权重 为了是切动画
            }
        },{
            path: "/userInfo",
            name: "userInfo",
            component: userInfo,
            meta: {
                isNeedLogin: true,
                title: "用户中心",
            }
        }
    ]
})

// 路由守卫的生命周期 -- 在进入页面前
router.beforeEach((to,form,next) => {

    // 1. 进入不同的页面 改变不同的标题
    document.title = to.meta.title

    // 2. 存储下sid 和openid
    if (to.query.sid && to.query.openid) {
        let {sid,openid} = to.query
        storage.set({sid,openid})
        if(storage.get("?token") && storage.get("?userInfo"))  next({ name: "index", replace: true })
    }

    // 3. 如果本地没有token和userInfo 要立即回跳到登录页面
    if(to.name != "login" && !storage.get("?token")) next({ name: "login", replace: true })


    // last. 最后正常到进入到页面
    next()
})

export default router
